import axios from "axios";
import { Message } from "element-ui";
import { jumpLogin } from "@/utils/index";

 //创建实例
  const instance = axios.create({
    baseURL:'http://123.60.134.119',//43.136.172.95   123.60.134.119
    timeout: 60000, //超时配置
    withCredentials: true, //跨域携带cookie
  
  });

  // 添加请求拦截器
  instance.interceptors.request.use(
    function (config) {
      // 在发送请求之前做些什么
      // console.log("config:", config);
      //token存在才可以进入页面  存userID
      if(window.sessionStorage.getItem('tokenStr')){
        config.headers.Authorization = window.sessionStorage.getItem('tokenStr')
        config.headers.userID=window.sessionStorage.getItem('userID')
      }

    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    // console.log("response:", response);
    // const { status, data, msg } = response.data;
    // const { status, data} = response.data;
    const { status } = response;
    if (status === 200) return response;
    else if (status === 401) {
      jumpLogin();
    } else {
      Message.error("error!发生错误!");

      return Promise.reject(response.data);
    }
  },
  function (error) {
    // 对响应错误做点什么
    console.log("error-response:", error.response);
    console.log("error-config:", error.config);
    console.log("error-request:", error.request);
    if (error.response) {
      if (error.response.status === 401) {
        jumpLogin();
      }
    }
    Message.error(error?.response?.data?.message || "服务端异常");
    return Promise.reject(error);
  }
);

export default instance;
